#include "SmdPadCalculatorWidget.h"
#include "ui_SmdPadCalculatorWidget.h"

#include "SmdPadCalculator.h"

SmdPadCalculatorWidget::SmdPadCalculatorWidget(QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::SmdPadCalculatorWidget),
    m_calculator(new SmdPadCalculator(this))
{
    m_ui->setupUi(this);

    bind("leadSpanMin", m_ui->lmin, 5.85);
    bind("leadSpanMax", m_ui->lmax, 6.2);
    bind("leadWidthMin", m_ui->tmin, 0.4);
    bind("leadWidthMax", m_ui->tmax, 1.27);
    bind("leadHeightMin", m_ui->wmin, 0.31);
    bind("leadHeightMax", m_ui->wmax, 0.51);

    bind("fabricationTolerance", m_ui->fabtol, 0.05);
    bind("placementTolerance", m_ui->placetool, 0.025);

    bind("toeGoal", m_ui->toegoal, 0.35);
    bind("heelGoal", m_ui->heelgoal, 0.35);
    bind("sideGoal", m_ui->sidegoal, 0.03);

    bind("positionRounding", m_ui->placernd, 0.02);
    bind("sizeRounding", m_ui->sizernd, 0.01);

    m_calculator->calculate();
    showResult();
}

SmdPadCalculatorWidget::~SmdPadCalculatorWidget()
{
    delete m_ui;
}

void SmdPadCalculatorWidget::bind(const QString &name, QDoubleSpinBox *spinBox, qreal value)
{
    spinBox->setValue(value);
    m_calculator->setProperty(name.toLocal8Bit().data(), QVariant(value));

    connect(spinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
            [this, name](double doubleValue) {
        m_calculator->setProperty(name.toLocal8Bit().data(), QVariant(doubleValue));
        m_calculator->calculate();
        showResult();
    });
}

void SmdPadCalculatorWidget::showResult()
{
    m_ui->c->setValue(m_calculator->padSpacing());
    m_ui->x->setValue(m_calculator->padWidth());
    m_ui->y->setValue(m_calculator->padHeight());
}
